﻿using AJWPFAdmin.Core.Logger;
using AJWPFAdmin.Services.AppointAPI;
using AJWPFAdmin.Services.EF;
using Microsoft.EntityFrameworkCore;
using Prism.Ioc;
using Quartz;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static AJWPFAdmin.Services.Jobs.CarExpiredCheckJob;

namespace AJWPFAdmin.Services.Jobs
{
    public class AppointAPIDataVerificationUploadJob : IAJJob
    {
        public class AppointAPIUploadQuarztJob : IJob
        {
            public async Task Execute(IJobExecutionContext context)
            {
                context.MergedJobDataMap.TryGetValue("container", out var container);
                if (container is IContainerProvider provider)
                {
                    var appointApiSvc = new AppointAPISvc(ApplicationType.管理端, provider);

                    if (appointApiSvc.API.Config.Key == Core.Enums.SystemConfigKey.APIDefault
                        || !appointApiSvc.API.AutoUploadDataVerification)
                    {
                        appointApiSvc.API.Dispose();
                        return;
                    }

                    var logger = provider.Resolve<AJLog4NetLogger>();

                    using var db = DbService.GetDbContext(provider.Resolve<AJConfigService>());

                    var @params = await DataVerificationParams.ComputeAsync(db);

                    var result = await appointApiSvc.API.UploadDataVerificationAsync(@params);

                    logger.Info($"{appointApiSvc.API.KeyDescription} 数据核查上传结果:{result.Message}");

                    appointApiSvc.API.Dispose();
                }
            }
        }

        public void Init(IContainerProvider container, IScheduler scheduler)
        {
            var jobData = new Dictionary<string, object> { { "container", container } };
            var map = new JobDataMap
            {
                { "container", container }
            };
            var key = nameof(AppointAPIDataVerificationUploadJob);
            var job = JobBuilder.Create<AppointAPIUploadQuarztJob>().WithIdentity(key)
                .SetJobData(map)
                .WithDescription("第三方放预约接口需要自动上传数据核查信息的定时任务").Build();
            // 每天23:59执行
            var trigger = TriggerBuilder.Create().WithIdentity(key).WithCronSchedule($"0 59 23 1/1 * ? *").Build();
            //var trigger = TriggerBuilder.Create().WithDailyTimeIntervalSchedule((b) =>
            //{
            //    b.WithIntervalInSeconds(10);
            //}).Build();

            scheduler.ScheduleJob(job, trigger);
        }
    }
}
